#!/bin/bash
#
# @@@ START COPYRIGHT @@@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
# @@@ END COPYRIGHT @@@
#

# Check if there are TM processes already running on the cluster.
# If they are, then it means that this script was executed before to
# start the TMs. 
lv_num_tm_processes=$(sqshell -c persist info DTM | grep DTM | wc -l)
echo "Number of TM processes on the instance: ${lv_num_tm_processes}"
if ( [ ${lv_num_tm_processes} '>' 0 ] ); then
    sqshell -c set SQ_TXNSVC_READY=1
fi

sqshell -a <<eof

! Start DTM
set DTM_RUN_MODE=2
set SQ_AUDITSVC_READY=1
set DTM_TLOG_PER_TM=1
set TRAF_TM_LOCKED=0
delay 5
exit
eof

sqcheck -c dtm -d 10 -i 60 -r
sq_stat_dtm=$?
if ([ $sq_stat_dtm '!=' 0 ] && [ $sq_stat_dtm '!=' 1 ]); then
    echo "The dtm process(es) are Not Ready yet. Stopping further startup (if any)."
    exit 1
else
    echo "The dtm process(es) are Ready."
fi
sqshell -a <<eof
! Generate DTM Event 1
event {DTM} 1
exit
eof

echo "Checking whether the transaction service is ready."
sqr_stat=0
while [[ $sqr_stat == 0 ]];
do
    sqregck -r SQ_TXNSVC_READY -d 5 -i -1
    sqr_stat=$?
done
echo "The Transaction Service is Ready."
